const resolveApp = require("./paths");
// copy public下的静态资源 favicon.icon
const CopyPlugin = require("copy-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { merge } = require('webpack-merge')
const HtmlWebpackPlugin = require("html-webpack-plugin");
// 导入抽取css的插件
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// 压缩css
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const commonConfig = require('./webpack.common.js')

module.exports = (env) => {
  // 在 package.json 中 设置 --env production
  // ----------------- { WEBPACK_BUNDLE: true, WEBPACK_BUILD: true, production: true }
  console.log('-----------------', env, process.env.NODE_ENV)
  return merge({
    output: {
      filename: "js/[name].bundle.js",
      // chunkFilename: 'js/[id].bundle.js',
      path: resolveApp('./dist'), // 打包生成目录
      publicPath: '/', // 所有输出资源引入时的公共路径，若loader中也配置了publicPath，会以loader为准。
    },
    mode: 'production',
    module: {
      rules: [

      ]
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: "webpack 搭建项目",
        template: "./public/index.html",
        minify: {
          collapseWhitespace: true, // 合并多余的空格
          removeComments: true, // 移除注释
          removeAttributeQuotes: true, // 移除属性上的双引号
          removeEmptyAttributes: true, // 移除空属性
          removeRedundantAttributes: true,  // 移除无用标签
          removeStyleLinkTypeAttributes: true,  // 移除 rel="stylesheet"
          useShortDoctype: true, // 使用短文档说明
          keepClosingSlash: true, // 自结束
          minifyCSS: true,  // 压缩 html 中的css
          minifyJS: true, // 压缩 js
          minifyURLs: true,  // 压缩 url
        }
      }),
      new CopyPlugin({
        patterns: [
          {
            from: "./public",
            to: resolveApp('./dist/public'),
            globOptions: {
              ignore: ["**/index.html"], // **/ 表示在当前public目录下查找
            },
          },
        ],
      }),
      new CleanWebpackPlugin(), // 每次构建打包之前清空之前的打包
      new MiniCssExtractPlugin({
        filename: 'css/[name].[hash:4].css',
      }),
      new OptimizeCSSAssetsPlugin({
        cssProcessorPluginOptions: {
          preset: ['default', { discardComments: { removeAll: true }}],
        },
        cssProcessorOptions: {
          map: {
            inline: false,
            annotation: true
          }
        }
      }),
      new BundleAnalyzerPlugin()
    ],
    // https://zhuanlan.zhihu.com/p/152097785?from_voters_page=true
    optimization: {
      // splitChunks: {
      //   chunks: "all",
      //   name: "vendor", // 相对 于 output.filename,与 output.filename 文件输出的路径同级 js/vendor
      //   cacheGroups: {
      //     lodash: {
      //       name: "lodash",
      //       chunks: "async",
      //       test: /[\\/]node_modules[\\/]lodash[\\/]/,
      //       priority: 40,  // 提取优先级
      //     },
      //     "async-common": {
      //       chunks: "async",
      //       minChunks: 2,
      //       name: "async-commons",
      //       priority: 50,
      //     },
      //     commons: {
      //       name: "commons",
      //       chunks: "all",
      //       minChunks: 2,
      //       priority: 120,
      //     },
      //   },
      // },
      splitChunks: {
        chunks: 'async',  // 提取异步加载模块
        minSize: 30000,  // 提取的模块在提取前的最小值，超过会被提取（默认30000）
        maxSize: 2000000,  // 提取之后打包生产的文件最大值，超过会被分割成新的文件（默认0）
        minChunks: 3,  // 被提取的模块的最小引用次数，超过或等于会被提取
        maxAsyncRequests: 6,  // 最大的异步加载次数（默认6）
        maxInitialRequests: 4,  // 打包后的入口文件，还能同时加载js文件的数量（包括入口 文件，默认4）
        automaticNameDelimiter: '~', // 打包生成的js文件名分割符（默认~）
        cacheGroups: {
          vendors: {
            name: `chunk-vendors`,
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
            minChunks: 1,
            chunks: 'all'
          },
          cjs: {
            name: `chunk-cjs`,
            test: /[\\/]cjs[\\/]/,
            priority: 10,
            minChunks: 1,
            chunks: 'all'
          },
          common: {
            name: `chunk-common`,
            minChunks: 2,
            priority: -20,
            chunks: 'initial',
            reuseExistingChunk: true  // 如果当前模块已被提取，则重用该模块，不会重新打包
          }
        }
      }
    },
  }, commonConfig)
}
